package com.amoby.base.utils.ftp;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class FTPFactory extends BasePooledObjectFactory<SFTPClient> {
    private String site;
    private String loginId;
    private String sshKeyPath;

    @Override
    public SFTPClient create() throws Exception {
        SFTPClient sftp = new SFTPClient(site, loginId, sshKeyPath);
        sftp.connect();
        return sftp;
    }

    @Override
    public PooledObject<SFTPClient> wrap(SFTPClient obj) {
        return new DefaultPooledObject<SFTPClient>(obj);
    }

    @Override
    public void destroyObject(PooledObject<SFTPClient> p) throws Exception {
        SFTPClient sftp = p.getObject();
        sftp.disconnect();
    }

    @Override
    public boolean validateObject(PooledObject<SFTPClient> p) {
        SFTPClient sftp = p.getObject();
        return sftp.isConnected();
    }

    @Override
    public void activateObject(PooledObject<SFTPClient> p) throws Exception {
        SFTPClient sftp = p.getObject();
        if (!sftp.isConnected()) {
            sftp.connect();
        }
    }

    public String getSite() {
        return this.site;
    }

    public String getLoginId() {
        return this.loginId;
    }

    public String getSshKeyPath() {
        return this.sshKeyPath;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public void setLoginId(String loginId) {
        this.loginId = loginId;
    }

    public void setSshKeyPath(String sshKeyPath) {
        this.sshKeyPath = sshKeyPath;
    }
}
